//
//  MainMessageViewController.m
//  ERP
//
//  Created by goldeney on 15/7/10.
//  Copyright (c) 2015年 ShangHai Goldeneye Techonology Co.,Ltd. All rights reserved.
//

#import "MessageCenterViewController.h"
#import "MainMessageViewCell.h"
#import "GETimeDifference.h"
#import "CustomBadge.h"

#import "QueryMessageService.h"
#import "NSDictionary+DataFormat.h"
#import "UITableView+Custom.h"

#import "OAMyBriefcaseViewController.h"
#import "OAMyApplyViewController.h"
#import "OAMyApprovalViewController.h"
#import "JCOrderListViewController.h"
#import "JCSubMViewController.h"
#import "OAMyMessageViewController.h"

#import "MessageInfoService.h"
#import "MessageInfoEntity.h"
#import <SDWebImage/UIImageView+WebCache.h>
#import "MessageInfoService.h"

#import "WebPushParameterModel.h"
#import "WebViewController.h"
#import "GEPushViewControllerHelper.h"

@interface MessageCenterViewController ()<MGSwipeTableCellDelegate>
{
    NSFetchedResultsController *fetchedResultsController;
}

@property (nonatomic,strong) NSMutableArray *listInfoArray;

@end

@implementation MessageCenterViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        [self setTitle:@"消息通知"];
        
        //添加菜单权限获取注册
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateMenuAuthorityService:)
                                                     name:MessageInfoServiceKey object:nil];
    }
    return self;
}

- (void)dealloc
{
    //移除菜单权限获取注册
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.listInfoArray = [NSMutableArray array];
    
    self.tableView.tableFooterView= [[UIView alloc] init];
    self.tableView.separatorColor = [UIColor colorWithWhite:0.90 alpha:1.0];
    
    //获取消息
    [MessageInfoService getMessageInfoSaveToSqlite];
    [self acquireChatData];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//获取数据和初始化
- (void)acquireChatData
{
    [self.listInfoArray removeAllObjects];
    
    NSArray *listArray = [MessageInfoEntity MR_findAllSortedBy:@"order" ascending:YES];;
    [self.listInfoArray addObjectsFromArray:listArray];
    if (listArray.count <= 0){
        [self.tableView setTableViewNotDataDrawText:@"暂无消息" isShow:YES];
        self.tableView.backgroundColor = [UIColor whiteColor];
    } else {
        [self.tableView setTableViewNotDataDrawText:nil isShow:NO];
    }
    
    [self.tableView reloadData];
}

#pragma mark -
#pragma mark - NSNotificationCenter

-(void)updateMenuAuthorityService:(NSNotification *)notification
{
    //获取消息信息
    if ([[notification name] isEqualToString:MessageInfoServiceKey]){
        [self acquireChatData];
    }
}

#pragma mark
#pragma mark - UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.listInfoArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *TableSampleIdentifier = @"MainMessageViewCell";
    MainMessageViewCell *cell = [tableView dequeueReusableCellWithIdentifier:TableSampleIdentifier];
    if (cell == nil){
        cell = [[MainMessageViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:TableSampleIdentifier];
    }
    
    cell.rightButtons = @[[MGSwipeButton buttonWithTitle:@"删除" backgroundColor:[UIColor redColor]]];
    cell.rightSwipeSettings.transition = MGSwipeTransition3D;
    cell.delegate = self;
    
    MessageInfoEntity *entity = [self.listInfoArray objectAtIndex:indexPath.row];
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    
    cell.titleLable.text = entity.title;
    cell.introduceLable.text = entity.content;
    cell.timeLable.hidden = YES;
    
    cell.iconView.contentMode = UIViewContentModeScaleToFill;
    [cell.iconView sd_setImageWithURL:[NSURL URLWithString:entity.icon] placeholderImage:[UIImage new]];
    
    //获取标记条数
    NSInteger numberBarge = [entity.readCount integerValue];
    if (numberBarge >0) {
        NSString *value = [NSString stringWithFormat:@"%ld",numberBarge];
        CustomBadge *badgeView = [CustomBadge customBadgeWithString:value];
        cell.accessoryView = badgeView;
    }

    return cell;
}

#pragma mark
#pragma mark - UITableViewDelegate

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [tableView setSeparatorInset:UIEdgeInsetsZero];
    }
    
    if ([tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [tableView setLayoutMargins:UIEdgeInsetsZero];
    }
    
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 58;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    MessageInfoEntity *entity = [self.listInfoArray objectAtIndex:indexPath.row];
    [MessageInfoService changeMessageUnreadState:entity.onlyTag];
    
    //modelType类型：0异常、1原生、2网页
    if(entity.modelType.integerValue == 2){
        //网页模式
        WebPushParameterModel *model = [[WebPushParameterModel alloc] init];
        model.URL = entity.webCode;
        model.Title = entity.title;
        model.CodeType = CodeTypeWeb;
        
        WebViewController *viewController = [[WebViewController alloc] initWithPushParameterModel:model];
        [self.navigationController pushViewController:viewController animated:YES];
    } else {
        //原生APP模式
        [GEPushViewControllerHelper pushViewControllerHomePageCode:entity.nativeCode navigation:self.navigationController];
    }
    
}

#pragma mark
#pragma mark - MGSwipeTableCellDelegate

-(BOOL) swipeTableCell:(MGSwipeTableCell*)cell tappedButtonAtIndex:(NSInteger) index direction:(MGSwipeDirection)direction fromExpansion:(BOOL)fromExpansion
{
    if (direction == MGSwipeDirectionRightToLeft && index == 0) {
        NSIndexPath *path = [_tableView indexPathForCell:cell];
        
        //删除改变状态
        MessageInfoEntity *entity = [self.listInfoArray objectAtIndex:path.row];
        [MessageInfoService changeMessageUnreadState:entity.onlyTag];
        
        //删除数据
        [entity MR_deleteEntity];
        [[NSManagedObjectContext MR_defaultContext] MR_saveToPersistentStoreAndWait];
        
        //delete button
        [self.listInfoArray removeObjectAtIndex:path.row];
        [_tableView deleteRowsAtIndexPaths:@[path] withRowAnimation:UITableViewRowAnimationLeft];
        return NO; //Don't autohide to improve delete expansion animation
    }
    
    return YES;
}

@end
